/**
 * 自定义信息窗口
 */
class CustomInfoBox extends BMapLib.InfoBox {
  static instances = []; // 已实例化的对象

  constructor(map, id, dom, opts = {}) {
    super(map, dom, {
      // boxStyle: {},
      hideCloseIcon: opts.hideCloseIcon || true,
      closeIconUrl: opts.closeIconUrl || 'static/bmap/images/close.png',
      closeIconClick: opts.closeIconClick || undefined,
      closeIconMargin: opts.closeIconMargin || '1px 1px 0 0',
      enableAutoPan: opts.enableAutoPan || false,
      align: INFOBOX_AT_TOP,
    });

    /**
     * 关闭
     */
    const close = () => {
      CustomInfoBox.instances = [];
      this.close();
      dom.firstChild.lastChild.removeEventListener('click', close);
    };
    dom.firstChild.lastChild.addEventListener('click', close);

    this.map = map;
    this.id = id;

    CustomInfoBox.instances.push(this);
  }

  // 打开InfoBox窗口
  open(marker) {
    // 只能打开一个InfoBox窗口
    CustomInfoBox.instances.forEach(i => {
      if (i !== this) this.map.removeOverlay(i);
    });
    super.open(marker);
  }

  /**
   * 是否打开信息窗口
   */
  static isOpen() {
    return this.instances.length > 0;
  }

  /**
   * 根据Id删除
   */
  static closeById(id) {
    if (!id) return;
    if (this.instances.length > 0) {
      this.instances.forEach(ins => {
        if (ins.id === id) ins.map.removeOverlay(ins);
        console.log('根据Id删除', id, ins);
      });
    }
  }

  /**
   * 关闭窗口
   */
  static closeBox() {
    if (this.instances.length > 0) {
      this.instances.forEach(ins => {
        ins.map.removeOverlay(ins);
      });
    }
  }
}

export default CustomInfoBox;
